package com.j1903.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;

public class UploadRile {
    /*
    *distFolder 保存文件的目录路径
    * request HttpServiceRequest 对象
     */
    public static String saveFile(HttpServletRequest request,
                           String distFolder
    ) {
        //判断请求中是否包含文件
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                if(new File(distFolder).exists()){
                    new File(distFolder).mkdirs();
                }
                //表单工厂对象
                FileItemFactory factory =
                        new DiskFileItemFactory();
                //初始化文件处理对象
                ServletFileUpload sfu =
                        new ServletFileUpload(factory);
                //获取所有的表单数据不管是字段还是文件
                List<FileItem> list =
                        sfu.parseRequest(request);

                for (FileItem item : list) {
                    //判断是否是表单字段
                    if (item.isFormField()) {
                        System.out.println("字段名" + item.getFieldName());
                        System.out.println("字段值" + item.getString("UTF-8"));
                    } else {
                        System.out.println("文件自段名" + item.getFieldName());
                        System.out.println("文件名" + item.getName());
                        //创建一个唯一的字符串作为新的文件名
                        String newFileName =
                                UUID.randomUUID().toString().replace("-", null);
                        //取文件拓展名
                        String extName = item.getName().substring(item.getName().indexOf("."));
                        //最终文件完整路径
                        String filePath =
                                distFolder + File.separator + newFileName + extName;
                        item.write(new File(filePath));
                        return newFileName+extName;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return null;
    }
}
